<template>
  <view class="login-text">验证码登录</view>
  <view>
    <Form ref="formRef" label-align="top" @submit="onSubmit">
      <CellGroup inset>
        <Field
          required
          label=""
          v-model="form.phone"
          name="phone"
          placeholder="手机号码"
          :rules="[
            { validator: validatorPhone, message: '请输入正确的手机号码' },
          ]"
        />
        <Field
          required
          label=""
          v-model="form.code"
          name="code"
          placeholder="验证码"
          :rules="[{ required: true, message: '请输入验证码' }]"
        >
          <template #button>
            <Button
              size="small"
              type="primary"
              :disabled="!!codetime"
              color="#01C1B0"
              @click="send"
              >{{ !codetime ? "获取验证码" : codetime + " s" }}</Button
            >
          </template>
        </Field>
        <Button
          style="margin-top: 30rpx"
          round
          block
          type="primary"
          native-type="submit"
          color="#01C1B0"
          >登录</Button
        >
      </CellGroup>
    </Form>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { Button, Form, Field, CellGroup, showFailToast } from "vant";
import type { FormInstance } from "vant";
import { onShow, onLoad } from "@dcloudio/uni-app";

const validatorPhone = (val: string) =>
  /^[1](([3][0-9])|([4][01456789])|([5][012356789])|([6][2567])|([7][0-8])|([8][0-9])|([9][012356789]))[0-9]{8}$/.test(
    val
  );

const form = reactive({
  phone: "",
  code: "",
});
const id = ref("");
const templateId = ref("");

// 根据手机号和验证码获取填报信息
const onSubmit = () => {
  uni.request({
    url: "/api/anon/fill/selectFillData",
    data: {
      phone: form.phone,
      code: form.code,
      templateId: templateId.value,
    },
    header: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    method: "GET",
    success: (res: any) => {
      const { code, data } = res.data;
      if (code === 200) {
        id.value = data.id;
        uni.navigateTo({
          url: `/pages/form/index?id=${id.value}&templateId=${templateId.value}`,
        });
      }
    },
  });
};

let codetime = ref(0);
const formRef = ref<FormInstance>();

// 发送验证码
const send = () => {
  formRef.value?.validate("phone").then((res) => {
    // 调接口发送短信
    uni.request({
      url: "/api/anon/common/sms",
      data: {
        phone: form.phone,
        template: "fillData",
      },
      header: {
        "Content-Type": "application/json",
      },
      method: "POST",
      success: (res: any) => {
        const { code, data } = res.data;
        if (code === 200) {
          // 发送成功，开启倒计时
          uni.showToast({
            title: "发送成功",
          });
          codetime.value = 60;
          let timer = setInterval(() => {
            codetime.value--;
            if (codetime.value < 1) {
              clearInterval(timer);
              codetime.value = 0;
            }
          }, 1000);
        } else {
          showFailToast(res.data.msg);
        }
      },
    });
  });
};

// 获取url中的模板id参数
const getQueryData = (name: string) => {
  const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  const search = window.location.href.split("?")[1] || "";
  const r = search.match(reg) || [];
  return r[2];
};

onLoad(() => {
  templateId.value = getQueryData("templateId");
});
</script>

<style lang="less">
.login-text {
  font-size: 50rpx;
  margin: 260rpx 40rpx 60rpx 40rpx;
}
</style>
